<template>
  <div>
    <!-- 头部搜索 start -->
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="关键词" prop="keyword">
        <el-input v-model="queryParams.keyword" placeholder="输入会员等级ID，会员等级名称、权益ID" clearable size="small" style="width: 300px" @keyup.enter.native="handleQuery" @clear="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="用户状态" size="small" style="width: 240px" @change="handleQuery">
          <el-option :key="10" label="全部" :value="10" />
          <el-option :key="1" label="已上架" :value="1" />
          <el-option :key="0" label="待上架" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small " @click="handleQuery">搜索</el-button>
        <el-button size="small " @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 头部搜索 end -->

    <!-- 头部操作栏 start -->
    <el-button type="primary" style="margin-bottom:10px" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
    <!-- 头部操作栏 end -->

    <!-- 表格数据 start -->
    <el-table v-loading="loading" :data="levelList">
      <el-table-column label="会员等级ID" width="100"  prop="level_id" />
      <el-table-column label="会员等级名称"  prop="name" />
      <el-table-column label="会员图标"

        prop="icon">
        <template slot-scope="scope">
          <el-image slot="reference"
            style="max-width: 72px; max-height: 36px;cursor: pointer;"
            :src="scope.row.icon"
            fit="contain"
            @click="handleImgClick(scope.row)"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="会员等级权重"  prop="weight" />
      <el-table-column label="等级级数"  prop="priority" />
      <el-table-column label="会员权益ID"  :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ getAttrs(scope.row.rights, 'right_id').join(',') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会员权益详情"  :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ getAttrs(scope.row.rights, 'name').join(',') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="充值人数"  prop="pay_count" />
      <el-table-column label="最近充值时间"  prop="last_pay_time" width="165">
        <template slot-scope="scope">
          <span>{{ scope.row.last_pay_time|parseTime() }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" >
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'" disable-transitions>{{ scope.row.status === 1 ? '已上架' : '待上架' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作"  width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small " type="text" @click="handleSale(scope.row)" :disabled="scope.row.status !== 0">上架</el-button>
          <el-button size="small " type="text" @click="handleUpdate(scope.row)" :disabled="scope.row.status !== 0">修改</el-button>
          <el-button size="small " type="text" @click="handleDelete(scope.row)" :disabled="scope.row.status !== 0">删除</el-button>
          <el-button size="small " type="text" >查看数据统计</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.page_size" @pagination="getList" />
    <!-- 表格数据 end -->

    <!-- 添加或修改对话框 start -->
    <el-dialog :title="title" :visible.sync="open" width="600px" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item v-if="form.level_id != undefined" label="会员等级ID" prop="id">
          <el-input v-model="form.level_id" disabled />
        </el-form-item>
        <el-form-item label="会员等级名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入会员等级名称" />
        </el-form-item>
        <el-form-item label="会员等级权重" prop="weight">
          <el-input-number v-model="form.weight" :min="0" :precision="0"></el-input-number>
        </el-form-item>
        <el-form-item label="等级级数" prop="priority">
          <el-input-number v-model="form.priority" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="会员权益" prop="right_id">
          <el-select multiple v-model="form.right_id" style="width:100%" placeholder="请选择" @change="$forceUpdate()">
            <el-option v-for="item in rightsOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="会员等级图标" prop="icon">
          <el-upload class="avatar-uploader"
          :action="upUrl+'admin-api/v1/upload'"
          accept="image/svg+xml"
          :show-file-list="false"
          :on-success="onUpload"
          :on-error="onUploadError"
          :before-upload="beforeUpload">
            <img v-if="form.icon" :src="form.icon" class="avatar">
            <div v-else class="avatar-uploader-icon">
              <i class="el-icon-plus"></i>
              <p>上传svg格式图片</p>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="form.level_id != undefined" @click="submitForm(0)">确 认</el-button>
        <el-button type="primary" v-if="form.level_id == undefined" @click="submitForm(0)">新增</el-button>
        <el-button type="primary" v-if="form.level_id == undefined" @click="submitForm(1)">新增并上架</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改对话框 end -->
  </div>
</template>

<script>
import { listLevel, delLevel, addLevel, updateLevel, updateStatus } from '@/api/member/level'
import { listRights } from '@/api/rights/rights'
export default {
  name: 'Level',
  data () {
    return {
      upUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 等级表格数据
      levelList: null,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      // statusOptions: [{ dictValue: 1, dictLabel: '已上架' }, { dictValue: 0, dictLabel: '待上架' }],
      // 权益选项
      rightsOptions: [],
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        keyword: undefined,
        status: 10
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '等级名称不能为空', trigger: 'blur' }
        ],
        icon: [
          { required: true, message: '请上传图标', trigger: 'blur' }
        ],
        right_id: [
          { required: true, message: '请选择会员权益', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getList()
  },
  methods: {
    /** 查询用户列表 */
    getList () {
      this.loading = true
      listLevel(this.queryParams).then(response => {
        this.levelList = response.data.list
        this.total = response.data.total || 0
        this.loading = false
      }
      )
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset () {
      this.form = {
        id: undefined,
        // deptId: undefined,
        name: undefined,
        icon: undefined,
        weight: 0,
        right_id: undefined,
        priority: 1
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset()
      listRights({ page: 1, page_size: 500 }).then(respense => {
        this.rightsOptions = respense.data.list
      })
      this.open = true
      this.title = '添加会员等级'
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset()
      listRights({ page: 1, page_size: 500 }).then(respense => {
        this.rightsOptions = respense.data.list
      })
      this.form = this.deepClone(row)
      const selcted_rightids = this.getAttrs(row.rights, 'id')
      this.form.right_id = selcted_rightids
      this.open = true
      this.title = '修改会员等级'
    },
    /** 上架按钮操作 */
    handleSale (row) {
      this.$confirm('是否确认上架等级编号为"' + row.level_id + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return updateStatus(row.level_id)
      }).then(() => {
        this.getList()
        this.msgSuccess('操作成功')
      })
    },
    /** 提交按钮 */
    submitForm (status) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.level_id !== undefined) {
            this.form.id = this.form.level_id
            delete this.form.rights
            updateLevel(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            this.form.status = status
            addLevel(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const levelId = row.level_id
      const { pageIndex, pageSize } = this.queryParams
      this.$confirm('是否确认删除等级编号为"' + levelId + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delLevel(levelId)
      }).then(() => {
        this.queryParams.pageIndex = this.getCurrentPage({ total: this.total, pageSize, pageIndex })
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => { this.msgError('删除失败') })
    },
    /** 图片上传成功处理 */
    onUpload (response) {
      if (response.code === 200) {
        this.form.icon = response.data.url
      } else {
        this.msgError('上传失败')
      }
    },
    onUploadError () {
      this.msgError('上传失败')
    },
    /** 图片上传之前处理 */
    beforeUpload (file) {
      if (file.type === 'image/svg+xml') return true
      this.msgError('上传图片只能是 SVG 格式!')
      return false
    },
    /** 查看图片 */
    handleImgClick ({ icon }) {
      const link = document.createElement('a')
      link.href = icon
      link.target = '_blank'
      link.click()
    }
  }
}
</script>
<style lang="scss">
.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  &:hover {
    border-color: #409eff;
  }
}
.avatar-uploader-icon {
  display: flex;
  flex-direction: column;
  justify-content: center;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  i{
    font-size: 28px;
  }
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
